<template>
  <div>
    <!-- 用例表单 -->
    <TestCaseForm
      @refresh="fetchCases"
      :editing-case="editingCase"
      @handle_update="handleUpdate"
      @handle_create="handleCreate"
      ref="caseFormRef"
    />

    <!-- 用例列表 -->
    <TestCaseList :cases="cases" @handle_update="handleEdit" @delete-case="handleDelete" />
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import TestCaseForm from '../components/TestCaseForm.vue'
import TestCaseList from '../components/TestCaseList.vue'
import api from '@/services/api'

const cases = ref([])
const editingCase = ref(null)
const caseFormRef = ref(null)

const fetchCases = async () => {
  try {
    const res = await api.get('test-cases/')
    cases.value = res.data.results.filter((item) => item && item.id)
  } catch (error) {
    // alert('获取用例失败: ' + error.message)
    console.log('error.message', error.message)
  }
}

const handleMis = async (payloads = {}, isEdit = false) => {
  try {
    let payload
    // ✅ 提交前：把 JSON 字符串解析成对象
    payload = isEdit
      ? {
          id: payloads.id,
          name: payloads.name,
          url: payloads.url,
          method: payloads.method,
          expected_status: payloads.expected_status,
          headers: payloads.headers || {}, // 直接用对象
          body: payloads.body || null,
          expected_response: payloads.expected_response || {},
        }
      : {
          name: payloads.name,
          url: payloads.url,
          method: payloads.method,
          expected_status: payloads.expected_status,
          headers: payloads.headers || {}, // 直接用对象
          body: payloads.body || null,
          expected_response: payloads.expected_response || {},
        }

    // ✅ 发送对象，axios 会自动 JSON.stringify
    if (isEdit) {
      // 编辑
      await api.put(`/test-cases/${payload.id}/`, payload)
      alert('编辑成功！')
    } else {
      await api.post('/test-cases/', payload)
      alert('创建成功！')
    }
  } catch (error) {
    console.error(error)
  }

  fetchCases()
}

// 安全解析 JSON 的工具函数
// function safeParse(jsonStr, fallback, fieldName) {
//   try {
//     const cleaned = (jsonStr || '').trim()
//     if (cleaned === '' || cleaned === 'null') return JSON.parse(fallback)
//     return JSON.parse(cleaned)
//   } catch (e) {
//     alert(`${fieldName} 格式错误：${e.message}`)
//     throw e // 阻止提交
//   }
// }

const handleUpdate = (payload) => {
  console.log('payload', payload)
  handleMis(payload, true)
}

const handleCreate = (payload) => {
  console.log('create')
  handleMis(payload)
}

const handleDelete = async () => {
  await fetchCases()
  if (!cases.length && caseFormRef.value) {
    caseFormRef.value.resetForm()
  }
}

const handleEdit = (caseItem) => {
  console.log('edit')
  editingCase.value = { ...caseItem }
}

// 初始加载
onMounted(() => {
  fetchCases()
})
</script>
